package order

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/order"
	"enjoy_xxz/internal/model/user"
	"enjoy_xxz/pkg"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

// 创建订单
func CreateOrder(data formdata.OrderCreateReq, userID int64) (string, error) {
	//查询用户地址
	u := user.UserAddress{
		Model:  gorm.Model{ID: uint(data.AddrId)},
		UserID: userID,
	}
	//地址详情
	addrInfo, err := u.GetAddrByAddrId()
	if err != nil {
		return "", err
	}
	o := new(order.Order)
	orderInfo, err := o.CreateOrder(data, addrInfo, int64(userID))
	if err != nil {
		return "", err
	}

	newpayData := pkg.NewPayData()
	payUrl, err := newpayData.Pay(&pkg.PayData{
		OutTradeNo:  orderInfo.No,           //订单号
		TotalAmount: orderInfo.Amount,       // 总金额
		Subject:     "测试订单",                 //标题
		ReturnUrl:   "http://www.baidu.com", // 跳转地址
		NotifyUrl:   "",                     //回调 地址
	})
	if err != nil {
		return "", err
	}
	return payUrl, nil
}

// 订单列表  可根据订单状态查询
func GetOrderList(data formdata.GetOrderListReq, userID int64) ([]formdata.OrderGoodsList, error) {
	status, _ := strconv.Atoi(data.Status)
	fmt.Println("订单状态", status)
	o := order.Order{
		UserID: userID,
		Status: int8(status),
	}
	return o.GetOrderGoodsList()
}

// 查询订单信息
func GetOrderGoodsById(data formdata.GetOrderGoodsById) (formdata.OrderGoodsInfo, error) {
	id, _ := strconv.Atoi(data.OrderId)
	o := new(order.OrderGoods)
	return o.GetOrderGoodsByIds(int64(id))
}
